<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
     <el-form-item label="区域" prop="deptId">
        <select-input dsCode="sys_dept_community" v-model="queryParams.deptId" style="width:180px"/>
      </el-form-item>  
      <el-form-item label="房屋" prop="roomId">
        <el-input v-model="queryRoomName" placeholder="请选择" readonly @click="doSelectRoom('query')" />
        <el-input v-model="queryParams.roomId" type="hidden" />
      </el-form-item>
      <el-form-item label="承租业主" prop="personId">
        <ds-remote dsCode="archive_person_remote" v-model="queryParams.personId" tips="请输入姓名或身份证号" style="width:180px;"/>
      </el-form-item>  
      <el-form-item label="开始日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeStartDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="缴费状态" prop="chargeStatus">
        <el-select v-model="queryParams.chargeStatus" placeholder="请选择" clearable style="width:120px">
          <el-option
            v-for="dict in charge_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['service:tenancy:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['service:tenancy:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tenancyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单位区域" align="center" prop="deptName" />
      <el-table-column label="楼栋" align="center" prop="buildingName" />
      <el-table-column label="单元号" align="center" prop="unitNum" />
      <el-table-column label="房屋号" align="center" prop="roomName" />
      <el-table-column label="承租业主" align="center" prop="personName" />
      <el-table-column label="租赁时长" align="center" prop="months" />
      <el-table-column label="月租金" align="center" prop="feeMonth" />
      <el-table-column label="总租金" align="center" prop="feeTotal" />
      <el-table-column label="押金" align="center" prop="feeDeposit" />
      <el-table-column label="开始日期" align="center" prop="startDate" width="180" />
      <el-table-column label="结束日期" align="center" prop="endDate" width="180" />
      <el-table-column label="合同" align="center" prop="contractFile">
        <template #default="scope">
    <el-link :href="baseUrl+scope.row.contractFile" target="_blank" v-if="scope.row.contractFile">下载</el-link>
    <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="说明" align="center" prop="remark" />
      <el-table-column label="缴费状态" align="center" prop="chargeStatus">
        <template #default="scope">
          <dict-tag :options="charge_status" :value="scope.row.chargeStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['service:tenancy:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['service:tenancy:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改租赁信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="tenancyRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="房屋" prop="roomId">
          <el-input v-model="formRoomName" placeholder="请选择" readonly @click="doSelectRoom('form')" />
          <el-input v-model="form.roomId" type="hidden" />
        </el-form-item>
        <el-form-item label="承租业主" prop="personId">
          <ds-remote dsCode="archive_person_remote" v-model="form.personId" tips="请输入姓名或身份证号"/>
        </el-form-item>
        <el-form-item label="租赁时长" prop="months">
          <el-input-number v-model="form.months" placeholder="请输入月数" @change="countFee"/>
        </el-form-item>
        <el-form-item label="月租金" prop="feeMonth">
          <el-input-number v-model="form.feeMonth" placeholder="请输入月租金" @change="countFee"/>
        </el-form-item>
        <el-form-item label="总租金" prop="feeTotal">
          <el-input-number v-model="form.feeTotal" placeholder="请输入总租金" @change="countFee"/>
        </el-form-item>
        <el-form-item label="押金" prop="feeDeposit">
          <el-input-number v-model="form.feeDeposit" placeholder="请输入押金" @change="countFee"/>
        </el-form-item>
        <el-form-item label="应收" prop="feeAll">
          <el-input-number v-model="form.feeAll" readonly/>
        </el-form-item>
        <el-form-item label="缴费状态" prop="chargeStatus">
          <el-select v-model="form.chargeStatus" placeholder="请选择" clearable style="width:120px">
            <el-option
              v-for="dict in charge_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker clearable
            v-model="form.startDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable
            v-model="form.endDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同" prop="contractFile">
          <file-upload v-model="form.contractFile"/>
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <room-select :show="showRoomSelect" :params="roomSelectParams" @select="selectRoom"/>

  </div>
</template>

<script setup name="Tenancy">
import { listTenancy, getTenancy, delTenancy, addTenancy, updateTenancy } from "@/api/service/tenancy";
import SelectInput from "@/components/FormInput/Select";
import DsRemote from "@/components/FormInput/Remote";
import RoomSelect from "@/components/Selection/Room";

const baseUrl = import.meta.env.VITE_APP_BASE_API;

const { proxy } = getCurrentInstance();
const { pay_way, sys_yes_no, charge_status } = proxy.useDict('pay_way', 'sys_yes_no', 'charge_status');

const tenancyList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeStartDate = ref([]);
const queryRoomName = ref("");
const formRoomName = ref("");
const showRoomSelect = ref(false);
const roomSelectParams = ref(null);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 't.id',
    isAsc: 'desc',
    deptId: null,
    roomId: null,
    personId: null,
    month: null,
    feeMonth: null,
    feeTotal: null,
    feeDeposit: null,
    startDate: null,
    endDate: null,
    contractFile: null,
    chargeStatus: null,
  },
  rules: {
    deptId: [
      { required: true, message: "区域不能为空", trigger: "blur" }
    ],
    roomId: [
      { required: true, message: "房屋不能为空", trigger: "blur" }
    ],
    personId: [
      { required: true, message: "承租业主不能为空", trigger: "blur" }
    ],
    months: [
      { required: true, message: "租赁时长不能为空", trigger: "blur" }
    ],
    feeMonth: [
      { required: true, message: "月租金不能为空", trigger: "blur" }
    ],
    feeTotal: [
      { required: true, message: "总租金不能为空", trigger: "blur" }
    ],
    feeDeposit: [
      { required: true, message: "押金不能为空", trigger: "blur" }
    ],
    chargeStatus: [
      { required: true, message: "缴费状态不能为空", trigger: "change" }
    ],
    startDate: [
      { required: true, message: "开始日期不能为空", trigger: "blur" }
    ],
    endDate: [
      { required: true, message: "结束日期不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询租赁信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeStartDate && '' != daterangeStartDate) {
    queryParams.value.params["beginStartDate"] = daterangeStartDate.value[0];
    queryParams.value.params["endStartDate"] = daterangeStartDate.value[1];
  }
  listTenancy(queryParams.value).then(response => {
    tenancyList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function doSelectRoom(params){
  roomSelectParams.value = params;
  showRoomSelect.value = true;
}
function selectRoom(room){
  showRoomSelect.value = false;
  if(room == null){
    form.value.roomId = null;
    formRoomName.value = null;
    queryParams.value.roomId = null;
    queryRoomName.value = null;
    return;
  }
  if(room.params == 'form'){
    form.value.roomId = room.id;
    formRoomName.value = room.name;
  }else{
    queryParams.value.roomId = room.id;
    queryRoomName.value = room.name;
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

function countFee(){
  if(form.value.feeMonth == null || form.value.months == null){
    form.value.feeAll = 0;
    return;
  }
  let fee = new Number(form.value.feeMonth) * new Number(form.value.months);
  form.value.feeTotal = fee
  fee += new Number(form.value.feeDeposit);
  form.value.feeAll = fee;
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    roomId: null,
    personId: null,
    months: null,
    feeMonth: null,
    feeTotal: null,
    feeDeposit: null,
    feeAll: null,
    startDate: null,
    endDate: null,
    contractFile: null,
    remark: null,
    chargeStatus: '0',
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("tenancyRef");
  formRoomName.value = null;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryRoomName.value = null;
  daterangeStartDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加租赁信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTenancy(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改租赁信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tenancyRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTenancy(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTenancy(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除选中的租赁信息数据项？').then(function() {
    return delTenancy(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service/tenancy/export', {
    ...queryParams.value
  }, `tenancy_${new Date().getTime()}.xlsx`)
}


getList();
</script>
